#!/usr/bin/env php
<?php
/*
 * This file is part of PHPUnit.
 *
 * (c) Sebastian Bergmann <sebastian@phpunit.de>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

use Swoole\Timer;

if (version_compare('7.1.0', \PHP_VERSION, '>'))
{
    fwrite(
        \STDERR,
        sprintf(
            'This version of PHPUnit is supported on PHP 7.1.' . \PHP_EOL .
            'You are using PHP %s (%s).' . \PHP_EOL,
            \PHP_VERSION,
            \PHP_BINARY
        )
    );

    exit(1);
}

foreach ([__DIR__ . '/../../autoload.php', __DIR__ . '/../vendor/autoload.php', __DIR__ . '/vendor/autoload.php'] as $file)
{
    if (file_exists($file))
    {
        define('PHPUNIT_COMPOSER_INSTALL', $file);

        break;
    }
}

unset($file);

if (!defined('PHPUNIT_COMPOSER_INSTALL'))
{
    fwrite(
        \STDERR,
        'You need to set up the project dependencies using Composer:' . \PHP_EOL . \PHP_EOL .
        '    composer install' . \PHP_EOL . \PHP_EOL .
        'You can learn all about Composer on https://getcomposer.org/.' . \PHP_EOL
    );

    exit(1);
}

$options = getopt('', ['prepend:']);

if (isset($options['prepend']))
{
    require $options['prepend'];
}

unset($options);

require PHPUNIT_COMPOSER_INSTALL;

$code = 0;
Swoole\Coroutine::create(function () use (&$code) {
    try
    {
        $code = PHPUnit\TextUI\Command::main(false);
    }
    catch (\Swoole\ExitException $e)
    {
        $code = $e->getStatus();
    }
    catch (PHPUnit\TextUI\Exception $e)
    {
        $previous = $e->getPrevious();
        if ($previous instanceof \Swoole\ExitException)
        {
            $code = $previous->getStatus();
        }
        else
        {
            throw $e;
        }
    }
    finally
    {
        if (version_compare(SWOOLE_VERSION, '4.4', '<'))
        {
            Swoole\Event::exit();
        }
        else
        {
            Timer::clearAll();
        }
    }
});
Swoole\Event::wait();
exit($code);
